<template>
	<view>
		<u-navbar title="支付" title-color="#333" back-icon-color="#333"></u-navbar>
		<view class="container">
			<view class="amount-group">
				<view class="payment-remain-time" v-if="payDetails.remaining_transaction_time > 0">
					交易剩余时间 {{ hour }}:{{ minutes }}:{{ seconds }}
				</view>
				<view class="payment-amount">￥<text>{{ orderData.amount }}</text></view>
				<view class="payment-timeout-tips"  v-if="payDetails.remaining_transaction_time > 0">超时订单将自动关闭</view>
				<view class="payment-timeout-tips"  v-else >请您尽快支付</view>
			</view>
			<view class="payment-selection-group">
				<text style="font-weight: bold;">选择支付方式</text>
				<view class="payment-selection-list">
					<u-radio-group v-model="paymethod" active-color="#FC7404">
						<view class="payment-selection-item" style="width: 100%;" @click="paymethod = 'Wechat';">
							<image class="image-round" src="@/static/login/weixinpay.png"></image>
							<text class="payment-name">微信支付</text>
							<u-radio name="Wechat"></u-radio>
						</view>
						<!-- <view class="payment-selection-item" style="width: 100%;" @click="paymethod='0';">
							<image class="image-round" :src="ICON_ALIPAY" style="background-color: #1977fb;"></image>
							<text class="payment-name">支付宝</text>
							<u-radio name="0"></u-radio>
						</view> -->
						<view class="payment-selection-item" style="width: 100%;" @click="paymethod = 'Balance';">
							<image class="image-rect" src="@/static/login/yuepay.png"></image>
							<text class="payment-name">余额支付</text>
							<u-radio name="Balance"></u-radio>
						</view>
					</u-radio-group>
				</view>
			</view>
				
			<!-- <view>
				<uni-popup ref="pwd" type="center" :animation="false">
					<view
						style="width: 80vw; background-color: #FFF; padding: 30rpx; border-radius: 10rpx; display: flex; flex-direction: column; align-items: center;">
						<view>请输入支付密码</view>
						<input
							style="width: 1rpx;height: 1rpx;font-size: 0.1rpx;caret-color: transparent;color: transparent;"
							class="input-item" adjust-position="false" auto-blur="true" @blur="inputCodeBlur"
							@input="inputCode" :focus="focus" type="number" :value="code" oneTimeCode maxlength="6" />
						<view class="code-list" @click="focusClick">
							<view class="code-item" v-for="(item,index) in 6" :key="index"
								:style="(index == code.length && focus ? 'border-color:#FC7404;':'')">
								{{ index >= code.length ? '' : '●'}}
							</view>
						</view>
						<view
							style="display: flex; flex-direction: row; margin-top: 40rpx; width: 100%; line-height: 70rpx; font-size: 32rpx;">
							<view style="flex: 1; width: 50%; text-align: center;" @click="pwdCancel">取消</view>
							<view style="flex: 1; width: 50%; text-align: center; color: #FC7404 ;" @click="pwdConfirm">
								确认</view>
						</view>
					</view>
				</uni-popup>
			</view> -->
			
			
			<!-- <web-view v-if="is_zfb" :src="body_zfb"></web-view> -->
			
			<!-- <view v-if="is_zfb" style="height: 300px;"> -->
				<!-- deuhdweodowedwehfiwefwejfkwejfjlwedj -->
				<!-- <rich-text :nodes="body_zfb"></rich-text> -->
				<!-- <u-parse :content="body_zfb" /> -->
				<!-- <u-parse :content="body_zfb" style="height: 200px;"></u-parse> -->
			<!-- </view> -->
			
		</view>
		<view style="height: 200rpx;"></view>
		<view style="width: 100%;position: fixed;bottom: 0;">
			<view style="background: #fff;display: flex;align-items: center;justify-content: center;
			padding: 34rpx 34rpx 54rpx 34rpx;font-size: 32rpx;">
				<view style="color: #fff;background: #0BB1EF;
				padding: 20rpx 0;border-radius: 60rpx;width: 100%;text-align: center;"
				@click="confirmPay">立即支付</view>
			</view>
		</view>
	</view>
</template>
<script src = "https://gw.alipayobjects.com/as/g/h5-lib/alipayjsapi/3.1.1/alipayjsapi.min.js"> </script> 
<script>
	import configUrl from '@/utils/config.js';
	import { request } from 'utils/request.js';
	export default {
		name: "OrderDetail",
		data() {
			return {
				isLoading: false,
				code: '', // 验证码字段
				focus: false, // input是否聚焦
				orderId: 0,
				orderData: {},
				paymethod: "Balance",
				payDetails: {},
				paidId: 0,
				deviceType: "",

				ICON_ALIPAY: configUrl.appurlImg + "/app/alipay.png",
				ICON_WECHAT: configUrl.appurlImg + "/app/wechat.png",
				ICON_WECHATPAY: configUrl.appurlImg + "/app/wechatpay.png",
				ICON_UNIONPAY: configUrl.appurlImg + "/app/unionpay.png",
				ICON_PURSE: configUrl.appurlImg + "/app/purse.png",

				timerBack: 0,
				// 自动刷新标记
				srcFilter: "",
				isBind: false,
				wxCode: '',
				timer:null,
				isdisabled:false,
				body_zfb:'khefkjhefkwrjhfwejf',
				is_zfb:false
			};
		},
		// computed: {
		//     hour() {
		//     	let h = Math.floor(this.payDetails.remaining_transaction_time / 3600);
		//     	if (h < 10) {
		//     		h = '0' + h;
		//     	}
		//     	return h;
		//     },
		//     minutes() {
		//     	let m = Math.floor(this.payDetails.remaining_transaction_time % 3600 / 60);
		//     	if (m < 10) {
		//     		m = '0' + m;
		//     	}
		//     	return m;
		//     },
		//     seconds() {
				
		//     	let s = this.payDetails.remaining_transaction_time % 60;
		//     	if(s < 10){
		//     		s = '0'+ s;
		//     	}
				
		//       return s;
		//     },
		// },
		// onUnload() {
		// 	this.clearTimer(); // 页面卸载时清除计时器
		// },
		// onShow() {
		// 	this.isdisabled=false
		// },
		onLoad(e) {
			let self = this;
			this.orderId = e.orderId;
			// const code = self.getUrlCode('code')
			// if (code !== null && code !== '') {
			// 	self.isBind = true;
			// 	self.wxCode = code;
			// }
			// if (e.filter != null) this.srcFilter = e.filter;

			// /*#ifdef APP-PLUS */
			// // console.log('APP');
			// this.deviceType = "app";
			// /*#endif*/
			// /*#ifdef MP-WEIXIN || H5*/
			// this.deviceType = "miniapp";
			// /*#endif*/

			this.orderDetails();
		},
		methods: {
			getUrlCode(name) {
				return decodeURIComponent((new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|$)').exec(location.href) ||
				[, ''
				])[1].replace(/\+/g, '%20')) || null
			},
			orderDetails(e) {
				let self = this;
				request.getWithToken({
					url: '/order/orderDetails',
					data: {order_id: this.orderId}
				}).then(res=>{
					console.log(res)
					self.orderData = res.data.orderData;
				})
				return;
				orderApi.getOrderPayInfo({
					orderId: this.orderId
				}).then((res) => {
					self.payDetails = res;
					self.isLoading = true;
					self.startTimer()
				});
			},
			clearTimer() {
			      clearInterval(this.timer);
			      this.timer = null;
			    },
			startTimer() {
			      this.timer = setInterval(() => {
			        if (this.payDetails.remaining_transaction_time > 0) {
			          this.payDetails.remaining_transaction_time -= 1;
			        } else {
			          this.clearTimer();
			        }
			      }, 1000);
			    },
			confirmPay() {
				let self = this;
				// uni.showLoading({
				// 	title: "正在创建支付订单"
				// });
				// uni.hideLoading();
				// this.isdisabled = true;
				request.getWithToken({
					url: '/pay/payment',
					data: {
						paytype: self.paymethod,
						order_id: self.orderId
					}
				}).then(res=>{
					console.log(res);
					uni.showToast({
						title: res.msg,
						duration: 2000,
						icon: 'none'
					});
					setTimeout(() => {
						// uni.navigateBack();
						uni.switchTab({
							url: '/pages/menu/home'
						});
						// uni.$emit('htmlRefresh', {});
					}, 600);
					// this.$refs.paging.complete(res.data.dataList);
				})
				return;
				switch (this.paymethod) {
					case '0':
					
						if (self.payDetails.paytype == 'amount') {
							payApi.payAmount({
								paytype: self.paymethod,
								orderId: self.orderId,
								device: 'wap'
							}).then(o => {
								uni.hideLoading();
								window.location.href = o;
							}).catch(ex => {
								uni.hideLoading();
							});
						} else {
							payApi.payDeposit({
								paytype: self.paymethod,
								orderId: self.orderId,
								device: 'wap'
							}).then(o => {
								uni.hideLoading();
								// self.is_zfb=true;
								// let txt = o;
								// let index_s = o.indexOf('">https:');
								// let index_e = o.indexOf('</a></div>');
								// console.log(index_s,index_e)
								
								// console.log(o.substring(index_s+2, index_e))
								// let ddd = 'oaFWIAtgdPM6p7jPIRZjq5mTSa%2BxQdw9VEsZqbDAee%2F26lNsLKJSCIYuCXicnJ4gsPXbUjEAKvk1SDqXl0oiogRvj2C58ZDK6CPv%2FaqdubKtICWuvSsOyTkH%2F4VGSg%3D%3D';
								// self.body_zfb = "https://openapi.alipay.com/gateway.do?charset=utf-8&app_id=2021004187611154&format=JSON&charset=utf-8&sign_type=RSA2&version=1.0&return_url=https%3A%2F%2Fwww.zxzp.com%2Fweb_yh%2F%23%2Fpages%2Fusers%2FPayment%3ForderId%3D635%26filter%3Dall&notify_url=https%3A%2F%2Fwww.zxzp.com%2Faddons%2Frenli%2Findex%2Ftest%2Fpaytype%2Falipay&timestamp=2024-10-19+21%3A00%3A52&biz_content=%7B%22out_trade_no%22%3A%22AL202410192100520000063574%22%2C%22total_amount%22%3A%220.01%22%2C%22subject%22%3A%22%5Cu8ba2%5Cu5355%5Cu5b9a%5Cu91d1%5Cu652f%5Cu4ed8%22%2C%22product_code%22%3A%22QUICK_WAP_WAY%22%7D&app_cert_sn=411cef6165de6b8623adb4ecea25e17c&alipay_root_cert_sn=687b59193f3f462dd5336e5abf83c5d8_02941eef3187dddf3d3b83462e1dfcf6&method=alipay.trade.wap.pay&sign=g0khno4gCVc60RKbX1%2FEyzvJ64v5QCI5Jvm3HD7%2BpSPMW1DZN6teswo5Ca6O2sYsbMoCicwQu0oeRvYsVUZ1czkKLlUhuEN26LSj2h%2FpQJAt82egBME3bTCCfLBemCl8J8DY%2BZz2iryKSeEK2qddtAh2D7U28Dxrk8M4KDaas3hngqGRkhsp2V8MbHUIPpaKDy3x4WDOg3PvElqJ26crp%2FqH"+ddd;
								window.location.href = o;
							}).catch(ex => {
								uni.hideLoading();
							});
						}
						break;
						// 微信支付
					case '1':
						/*#ifdef H5*/
						console.log(11111111)
						// if (!self.isBind) {
						// 	window.location.href =
						// 		'https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx6b40132258f4bee2' +

						// 		'&redirect_uri=' + encodeURIComponent(
						// 			'https://rldemo.smomotbo.com/web_yh/#/') +
						// 			//pages/users/goods/pay?orderId='+self.orderId
						// 		'&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect';

						// }

						userApi.weixingLogin({
							orderId: self.orderId,
							code: self.wxCode
						}).then(r => {
							console.log(r)
							if (!r.status) {
								let local = encodeURIComponent(window.location.href); //获取当前页面地址作为回调地址

								let appid = 'wx6b40132258f4bee2'
								//通过微信官方接口获取code之后，会重新刷新设置的回调地址【redirect_uri】
								window.location.href =
									"https://open.weixin.qq.com/connect/oauth2/authorize?appid=" +
									appid +
									"&redirect_uri=" +
									local +
									"&response_type=code&scope=snsapi_userinfo&state=1#wechat_redirect";

							} else {
								if (self.payDetails.paytype == 'amount') {
									payApi.payAmount({
										paytype: self.paymethod,
										orderId: self.orderId,
										device: self.deviceType,
										openId: r.openid
									}).then(o => {
										self.requestWechatPay(o);
									}).catch(ex => {
										uni.hideLoading();
									});
								} else {
									payApi.payDeposit({
										paytype: self.paymethod,
										orderId: self.orderId,
										device: self.deviceType,
										openId: r.openid
									}).then(o => {
										self.requestWechatPay(o);
									}).catch(ex => {
										uni.hideLoading();
									});
								}
							}

						});


						/*#endif*/

						/*#ifdef MP-WEIXIN*/
						uni.login({
							provider: 'weixin',
							success(res) {
								userApi.getWechatOpenId({
									code: res.code
								}).then(r => {
									if (self.payDetails.paytype == 'amount') {
										payApi.payAmount({
											paytype: self.paymethod,
											orderId: self.orderId,
											device: self.deviceType,
											openId: r.openid
										}).then(o => {
											self.requestWechatPay(o);
										}).catch(ex => {
											uni.hideLoading();
										});
									} else {
										payApi.payDeposit({
											paytype: self.paymethod,
											orderId: self.orderId,
											device: self.deviceType,
											openId: r.openid
										}).then(o => {
											self.requestWechatPay(o);
										}).catch(ex => {
											uni.hideLoading();
										});
									}
								});
							},
							fail(e) {
								uni.hideLoading();
							}
						});
						/*#endif*/
						break;
					case '2':
						this.isdisabled = true;
						request.postWithToken({
							url: '/pay/payment',
							data: {
								// paytype: self.paymethod,
								orderId: self.orderId
							}
						}).then(res=>{
							console.log(res)
							// this.$refs.paging.complete(res.data.dataList);
						})
						return;
						if (self.payDetails.paytype == 'amount') {
							payApi.payAmount({
								paytype: self.paymethod,
								orderId: self.orderId
							}).then(o => {
								uni.hideLoading();
								self.paidId = o.id;
								self.$refs.pwd.open();
							});
						} else {
							payApi.payDeposit({
								paytype: self.paymethod,
								orderId: self.orderId
							}).then(o => {
								if(o.amount == -99){
									uni.showToast({
										title: '请先设置支付密码！',
										duration: 2000,
										icon: 'none'
									});
									setTimeout(() => {
										uni.navigateTo({
											url: '/pages/users/PayPassword'
										})
									},2000);
									return
								}
								uni.hideLoading();
								self.paidId = o.id;
								self.$refs.pwd.open();
							}).fail(e =>{
								console.log(e,'12312313123123')
							});
						}
						break;
				}


				// switch (this.paymethod) {
				//   case '0':

				//     break;
				//   case '1':
				//   if (this.payDetails.paytype == 'amount') {
				//       payApi.payAmount({paytype: this.paymethod, orderId: this.orderId}).then((res) => {
				//         self.paidId = res.id;
				//         // self.$refs.pwd.open();
				//       });
				//     } else {
				//       payApi.payDeposit({paytype: this.paymethod, orderId: this.orderId}).then((res) => {
				//         self.paidId = res.id;
				//         // self.$refs.pwd.open();
				//       });
				//     }
				//     break;
				//   case '2':
				//     if (this.payDetails.paytype == 'amount') {
				//       payApi.payAmount({paytype: this.paymethod, orderId: this.orderId}).then((res) => {
				//         self.paidId = res.id;
				//         self.$refs.pwd.open();
				//       });
				//     } else {
				//       payApi.payDeposit({paytype: this.paymethod, orderId: this.orderId}).then((res) => {
				//         self.paidId = res.id;
				//         self.$refs.pwd.open();
				//       });
				//     }
				//     break;
				// }
			},
			/**
			 * 发起微信支付
			 */
			requestWechatPay(o) {
				let self = this;

				/*#ifdef MP-WEIXIN*/

				uni.requestPayment({
					timeStamp: o.timeStamp,
					nonceStr: o.nonceStr,
					package: o.package,
					signType: o.signType,
					paySign: o.paySign,
					success() {
						uni.hideLoading();
						uni.showToast({
							title: '支付成功',
							duration: 2000,
							icon: 'none'
						});
						if (self.srcFilter) {
							uni.$emit('refreshOrder', self.srcFilter);
						}
						self.timerBack = setInterval(function() {
							clearInterval(self.timerBack);
							uni.navigateBack();
						}, 2000);
					},
					fail() {
						uni.hideLoading();
						uni.showToast({
							title: '用户取消支付',
							duration: 2000,
							icon: 'none'
						});
					}
				});

				/*#endif*/


				/*#ifdef H5*/

				let params = {
					appId: o.appId, //公众号ID，由商户传入
					timeStamp: o.timeStamp.toString(), //时间戳，自1970年以来的秒数
					nonceStr: o.nonceStr, //随机串
					package: o.package,
					signType: o.signType, //微信签名方式：
					paySign: o.paySign, //微信签名
				}

				WeixinJSBridge.invoke(
					"getBrandWCPayRequest",
					params,
					function(res) {

						uni.hideLoading();
						console.log(res, "res")
						if (res.err_msg == "get_brand_wcpay_request:ok") {
							uni.redirectTo({
								url: `/pages/users/OrderTabbar`,
							});
						} else {
							uni.showToast({
								title: '用户取消支付',
								duration: 2000,
								icon: 'none'
							});
						}
					})


				/*#endif*/
				// uni.requestPayment({
				//   timeStamp: o.timeStamp,
				//   nonceStr: o.nonceStr,
				//   package: o.package,
				//   signType: o.signType,
				//   paySign: o.paySign,
				//   success() {
				//   uni.hideLoading();
				//     uni.showToast({
				//       title: '支付成功',
				//       duration: 2000,
				//       icon: 'none'
				//     });
				//     if (self.srcFilter) {
				//       uni.$emit('refreshOrder', self.srcFilter);
				//     }
				//     self.timerBack = setInterval(function(){
				//       clearInterval(self.timerBack);
				//       uni.navigateBack();
				//     }, 2000);
				//   },
				//   fail() {
				//     uni.hideLoading();
				//     uni.showToast({
				//       title: '用户取消支付',
				//       duration: 2000,
				//       icon: 'none'
				//     });
				//   }
				// });
			},
			focusClick() {
				this.focus = true
			},
			// 输入框失去焦点
			inputCodeBlur(e) {
				let value = e.detail.value
				this.focus = false
			},
			// 输入框聚焦时触发（没用到）
			inputFocus(e, height) {
				console.log(e)
			},
			// 输入框内容变化事件
			inputCode(e) {
				let value = e.detail.value
				this.code = value
			},
			pwdCancel() {
				this.paidId = 0;
				this.code = '';
				this.$refs.pwd.close();
			},
			pwdConfirm() {
				// 提交余额支付
				payApi.confirmBalancePay({
					paidId: this.paidId,
					pwdstr: this.code
				}).then((res) => {
					this.$refs.pwd.close();
					uni.showToast({
						title: '支付成功',
						duration: 2000,
						icon: 'none',
					})
					let cd = setInterval(() => {
						clearInterval(cd);
						uni.navigateTo({ url: '/pages/users/Order?selectedId=0' });
						// uni.navigateBack();
					}, 2000);
				});
			}
		},
	};
</script>

<style lang="scss" scoped>
	.container {
		// position: absolute;
		// display: flex;
		// flex-direction: column;
		// justify-items: flex-start;
		padding: 0 30rpx;
		// height: 100vh;
		.amount-group {
			margin-top: 60rpx;
			margin-bottom: 60rpx;
			display: flex;
			flex-direction: column;
			align-items: center;

			.payment-remain-time {
				font-size: 24rpx;
				color: #777;
			}

			.payment-amount {
				margin-top: 20rpx;
				color: #fd9036;
				font-size: 40rpx;

				text {
					font-size: 48rpx;
				}
			}

			.payment-timeout-tips {
				font-size: 26rpx;
				color: #777;
				margin-top: 20rpx;
			}
		}

		.payment-selection-group {
			flex: 1;

			.payment-selection-list {
				display: flex;
				flex-direction: column;
			}

			.payment-selection-item {
				display: flex;
				flex-direction: row;
				margin-top: 40rpx;
				align-items: center;

				.image-round {
					width: 60rpx;
					height: 60rpx;
					// background-color: #000;
					// border-radius: 50%;
					margin-right: 20rpx;
				}

				.image-rect {
					width: 60rpx;
					height: 60rpx;
					margin-right: 20rpx;
				}

				.payment-name {
					flex: 1;
				}
			}
		}

		.payment-confirm {
			margin-bottom: 30rpx;
			margin-left: 5vw;
			margin-right: 5vw;
			background-color: #fd9036;
			color: #fff;
			border-radius: 30rpx;
			width: 90vw;
		}
	}

	.input-item {
		width: 0rpx;
		height: 0rpx;
	}

	.code-list {
		width: 100%;
		display: flex;
		align-items: center;
		justify-content: space-between;
		margin-top: 40rpx;

		.code-item {
			width: 80rpx;
			height: 80rpx;
			text-align: center;
			line-height: 80rpx;
			border: 1rpx solid #eee;
			background-color: #F6F6F6;
			border-radius: 10rpx;
		}
	}
</style>